﻿/* Copyright (c) 2010, John Cronin
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the copyright holder nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

/* Support copying of value types */

using System;
using System.Collections.Generic;
using System.Text;

namespace tysila
{
    partial class x86_64_Assembler
    {
        List<OutputBlock> do_memcpy(int size)
        {
            int chunk = 8;
            while ((size % chunk) != 0)
                chunk /= 2;

            int chunks = size / chunk;

            List<OutputBlock> ret = new List<OutputBlock>();
            ret.Add(new CodeBlock { Code = EncOpcode(0, Rcx, 3, true, chunks, 0xc7) }); // mov rcx, chunks

            switch (chunk)
            {
                case 8:
                    ret.Add(new CodeBlock { Code = new byte[] { 0xf3, 0x48, 0xa5 } });
                    break;
                case 4:
                    ret.Add(new CodeBlock { Code = new byte[] { 0xf3, 0xa5 } });
                    break;
                case 2:
                    ret.Add(new CodeBlock { Code = new byte[] { 0x66, 0xf3, 0xa5 } });
                    break;
                case 1:
                    ret.Add(new CodeBlock { Code = new byte[] { 0xf3, 0xa4 } });
                    break;
                default:
                    throw new Exception("Invalid chunk size");
            }

            return ret;
        }

        IEnumerable<OutputBlock> x86_64_memcpy_smem_dmem(ThreeAddressCode.Op op, var result, var op1, var op2,
            ThreeAddressCode tac, AssemblerState state)
        {
            /* lea source to rsi, dest to rdi */
            List<OutputBlock> ret = new List<OutputBlock>();

            ret.Add(new CodeBlock { Code = EncOpcode(Rsi, op1.hardware_loc, 3, true, 0, 0x8d) });
            ret.Add(new CodeBlock { Code = EncOpcode(Rdi, result.hardware_loc, 3, true, 0, 0x8d) });

            ret.AddRange(do_memcpy(tac.VTSize.Value));            

            return ret;
        }

        IEnumerable<OutputBlock> x86_64_memcpy_srsi_dmem(ThreeAddressCode.Op op, var result, var op1, var op2,
            ThreeAddressCode tac, AssemblerState state)
        {
            /* lea dest to rdi */
            List<OutputBlock> ret = new List<OutputBlock>();

            ret.Add(new CodeBlock { Code = EncOpcode(Rdi, result.hardware_loc, 3, true, 0, 0x8d) });

            ret.AddRange(do_memcpy(tac.VTSize.Value));

            return ret;
        }
        
        IEnumerable<OutputBlock> x86_64_memcpy_smem_drdi(ThreeAddressCode.Op op, var result, var op1, var op2,
            ThreeAddressCode tac, AssemblerState state)
        {
            /* lea source to rsi */
            List<OutputBlock> ret = new List<OutputBlock>();

            ret.Add(new CodeBlock { Code = EncOpcode(Rsi, op1.hardware_loc, 3, true, 0, 0x8d) });

            ret.AddRange(do_memcpy(tac.VTSize.Value));

            return ret;
        }

        IEnumerable<OutputBlock> x86_64_memcpy_srsi_drdi(ThreeAddressCode.Op op, var result, var op1, var op2,
            ThreeAddressCode tac, AssemblerState state)
        {
            return do_memcpy(tac.VTSize.Value);
        }

        IEnumerable<OutputBlock> x86_64_zeromem_o1rdi_o2const(ThreeAddressCode.Op op, var result, var op1, var op2,
            ThreeAddressCode tac, AssemblerState state)
        {
            // Zero a portion of memory

            int size = (int)op2.constant_val;
            int count = 0;
            int block_size = 0;
            if((size % 8) == 0)
            {
                block_size = 8;
                count = size / 8;
            }
            else if((size % 4) == 0)
            {
                block_size = 4;
                count = size / 4;
            }
            else if((size % 2) == 0)
            {
                block_size = 2;
                count = size / 2;
            }
            else
            {
                block_size = 1;
                count = size;
            }

            // Load rcx with the count
            List<OutputBlock> ret = new List<OutputBlock>();
            ret.Add(new CodeBlock(EncAddOpcode(Rcx, false, 0x8b, ToByteArrayZeroExtend(count, 4)), new x86_64_Instruction { opcode = "mov", Operand1 = Rcx, Operand2 = new const_location { c = count } }));
            // Load rax with 0
            ret.Add(new CodeBlock(new byte[] { 0x48, 0x31, 0xc0 }, new x86_64_Instruction { opcode = "xor", Operand1 = Rax, Operand2 = Rax }));

            // Do rep stos
            switch (block_size)
            {
                case 1:
                    ret.Add(new CodeBlock(new byte[] { 0xf3, 0xaa }, new x86_64_Instruction { opcode = "rep stosb" }));
                    break;
                case 2:
                    ret.Add(new CodeBlock(new byte[] { 0x66, 0xf3, 0xab }, new x86_64_Instruction { opcode = "rep stosw" }));
                    break;
                case 4:
                    ret.Add(new CodeBlock(new byte[] { 0xf3, 0xab }, new x86_64_Instruction { opcode = "rep stosd" }));
                    break;
                case 8:
                    ret.Add(new CodeBlock(new byte[] { 0xf3, 0x48, 0xab }, new x86_64_Instruction { opcode = "rep stosq" }));
                    break;
            }
            
            return ret;
        }
    }
}
